package top.chenyaohua.http;

import java.io.*;
import java.util.*;
import java.util.function.BiFunction;

public class HttpRequest {

    private OutputStream outputStream;

    private InputStream inputStream;
    /**
     * 协议
     */
    private String agreement;
    /**
     * 版本
     */
    private String version;
    /**
     *
     */
    private String url;
    /**
     *
     */
    private HttpMethod method;

    private Map<String,String> header;

    private Map<String,String> params;

    public HttpRequest (OutputStream outputStream, InputStream inputStream) {
        this.outputStream = outputStream;
        this.inputStream = inputStream;
        this.init();
    }

    private void init(){

        try {

            HashMap<String,String> temp = new HashMap<>();
            List<Integer> bt = new ArrayList<>();

            int tmps = 0;
            int sum = 0;
            while ( (tmps = inputStream.read())!=-1){
                bt.add(tmps);
                if(tmps ==10){
                    byte [] bts = new byte[bt.size()];
                    for (int i = 0; i < bt.size(); i++) {
                        bts[i] =  (byte) bt.get(i).intValue();
                    }
                    String line = new String(bts);

                    if(sum == 0){
                        //请求行
                        buildeRequestLine(line);
                        //请求行解析后才有url
                        this.params = getRequestParams(url);
                    }else{
                        if(line.equals("\r\n") ){
                            break;
                        }
                        int index = line.indexOf(":");
                        String value = line.substring(index + 1).trim();
                        String name = line.substring(0, index);
                        temp.put(name,value);
                    }
                    sum++;
                    bt = new ArrayList<>();
                }
            }

            this.header = new RequestMap(temp);

        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /**
     *
     * @param requestLine
     */
    private void buildeRequestLine (String requestLine) {

        String[] s = requestLine.split(" ");
        //请求方式
        switch (s[0].toUpperCase()){
            case "GET":
                this.method = HttpMethod.GET;
                break;
            case "DELETE":
                this.method = HttpMethod.DELETE;
                break;
            case "PUT":
                this.method = HttpMethod.PUT;
                break;
            default:
                this.method = HttpMethod.POST;
        }

        //请求路径
        this.url = s[1];

        //请求协议
        String[] sp = s[2].split("/");
        this.agreement = sp[0];
        this.version = sp[1];

    }

    private Map<String, String> getRequestParams (String url) {
        Map<String,String> params = new HashMap<>();
        if( (url.indexOf("?") != -1) && url.indexOf("?")<url.length() ){

            Arrays.stream(url.substring(url.indexOf("?")+1).split("&")).map(x->x.split("=")).forEach(x->params.put(x[0],x[1]));
        }
        return params;
    }


    public Map<String, String> getParams () {
        return params;
    }

    public String getParam (String name) {
        return params.get(name);
    }

    public OutputStream getOutputStream () {
        return outputStream;
    }

    public InputStream getInputStream () {
        return inputStream;
    }

    public String getAgreement () {
        return agreement;
    }

    public String getVersion () {
        return version;
    }

    public String getUrl () {
        return url;
    }

    public HttpMethod getMethod () {
        return method;
    }

    public Map<String, String> getHeader () {
        return header;
    }

    protected void setHeader (HashMap<String, String> header) {
        this.header = header;
    }

    /**
     *请求头信息
     */
    public static class RequestMap extends HashMap<String,String>{

        public RequestMap (HashMap<String,String> map) {
            super();
            super.putAll(map);
        }

        @Override
        public String put (String key, String value) {
            throw new RuntimeException("不允许添加");
        }

        @Override
        public void putAll (Map<? extends String, ? extends String> m) {
            throw new RuntimeException("不允许添加");
        }

        @Override
        public String remove (Object key) {
            throw new RuntimeException("不允许删除");
        }

        @Override
        public void clear () {
            throw new RuntimeException("不允许清空");
        }

        @Override
        public String putIfAbsent (String key, String value) {
            throw new RuntimeException("不允许添加");
        }

        @Override
        public boolean remove (Object key, Object value) {
            throw new RuntimeException("不允许删除");
        }

        @Override
        public boolean replace (String key, String oldValue, String newValue) {
            throw new RuntimeException("不允许替换");
        }

        @Override
        public String replace (String key, String value) {
            throw new RuntimeException("不允许替换");
        }

        @Override
        public void replaceAll (BiFunction<? super String, ? super String, ? extends String> function) {
            throw new RuntimeException("不允许替换");
        }
    }

}
